<script>
//这里就有大问题，没有他那个request
import request from "@/utils/class";
let socket;
export default {
  data() {
    return {
      circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      user: {},
      // isCollapse: false,
      users: [],
      chatUser: '',
      // text: "",
      // messages: [],
      // content: ''
    }
  }
}
</script>
<template>
  <div style="padding: 10px; margin-bottom: 50px">
    <!--      这里是显示在线人数和用户-->
    <el-icon><ChatDotRound /></el-icon>

    <el-row>
      <el-col :span="6">
        <el-card style="width: 95%; min-height: 300px; color: #333" v-if="!loading">
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">在线用户<span style="font-size: 12px">（点击聊天气泡开始聊天）</span></div>
          <!--          <div style="margin-left: 70px">群聊<button @click="clickchatUser2">chat</button>-->
          <!--            <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="chatUser === ''">chatting...</span>-->
          <!--          </div>-->
          <div style="padding: 10px 0" v-for="user in users" :key="user.username">
            <span>{{user.username}}</span>
            <button @click="clickchatUser(user.username)">chat</button>
            <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser">chatting...</span>
          </div>
        </el-card>
      </el-col>
      <!--        这里是聊天输入框-->
      <el-col :span="15">
        <div style="width: 800px; margin: 0 auto; background-color: white;
                    border-radius: 5px; box-shadow: 0 0 10px #ccc">
          <!--          <div style="text-align: center; line-height: 50px;margin-left: 120px;font-size: larger"-->
          <!--               v-if="chatUser === ''">-->
          <!--            万人聊天室-->
          <!--            <div style="float: right;margin-right: 10px;font-size: smaller">-->
          <!--              欢迎您：{{ username }}-->
          <!--            </div>-->
          <!--          </div>-->
          <div style="text-align: center; line-height: 50px;margin-left: 120px;font-size: larger" v-if="chatUser!== ''">
            <span id="chatUserDisplayName">{{chatUser}}</span>
            <div style="float: right;margin-right: 10px;font-size: smaller">
              欢迎您：{{ username }}
            </div>
          </div>
          <div style="height: 350px; overflow:auto; border-top: 1px solid #ccc" v-html="receivedMessage"></div>
          <div style="height: 200px">
            <textarea v-model="message" style="height: 160px; width: 95%; padding: 20px; border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; outline: none" @keydown.enter="sendMessage"></textarea>
            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" size="mini" @click="sendMessage">发送</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  <!--  下面真实上面测试-->
  <!--            <div>-->
  <!--              <h3>springboot项目websocket测试demo</h3>-->
  <!--              <h4>测试说明</h4>-->
  <!--              <h5>文本框中数据数据，点击‘发送测试’，文本框中的数据会发送到后台websocket，后台接受到之后，会再推送数据到前端，展示在下方；点击关闭连接，可以关闭该websocket；可以跟踪代码，了解具体的流程；代码上有详细注解</h5>-->
  <!--              <br />-->
  <!--              <input id="text" type="text" v-model="message" />-->
  <!--              <button @click="sendMessage">发送测试</button>-->
  <!--              <hr />-->
  <!--              <button @click="closeConnection">关闭连接</button>-->
  <!--              <hr />-->
  <!--              <div id="message">{{ receivedMessage }}</div>-->
  <!--            </div>-->
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount, reactive} from 'vue';
import {ChatDotRound} from 'element-plus'

const websocket = ref(null);
let user = {};
let message = ref('');
const loading = ref(true);
let chatUser = '';
let users = [];
let users2lenth = -1;
const receivedMessage = ref('');
// let username =  sessionStorage.getItem('username');
let username =  ''
let loginUser =  JSON.parse(sessionStorage.getItem('loginUser'))
let sname = loginUser.sname;
let mname = loginUser.mname;
let tname = loginUser.tname;
let aname = loginUser.aname;

console.log('sanme:'+sname)
console.log('mname:'+mname)
console.log('tname:'+tname)
console.log('aname:'+aname)
console.log('username:'+username)
if (sname !== undefined) {
  username = sname
}else if (mname !== undefined) {
  username = mname
}else if (tname !== undefined) {
  username = tname
}else if (aname !== undefined) {
  username = aname
}
// }
// if (sname !== null || sname.trim().length > 0) {
//     username = sname
// }else if (mname !== null || mname.trim().length > 0) {
//   username = mname
// }else if (tname !== null || tname.trim().length > 0) {
//   username = tname
// }else if (aname !== null || aname.trim().length > 0) {
//   username = aname
// }
console.log('username:'+username)
let chartchange = 0;
const clickchatUser = (nowname) => {
  chatUser = nowname
  receivedMessage.value = ''
  chartchange = 1;

  // 假设显示聊天对象名字的元素有一个特定的 ID，例如 "chatUserDisplayName"
  document.getElementById('chatUserDisplayName').textContent = nowname;
  console.log(chatUser)

  // 在此处获取并显示与当前聊天用户的历史聊天记录
  if (nowname) {
    let existingMessages = getMessagesForChatUser(nowname);
    existingMessages.forEach(message => {
      createContent2(message.from, message.to === username? username : null, message.content);
    });
  }
};
const clickchatUser2 = () => {
  chatUser = ''
  receivedMessage.value = ''
  chartchange = 1;
  console.log(chatUser)
};
const setMessageInHtml = (message) => {
  receivedMessage.value += message;
};

const closeConnection = () => {
  if (websocket.value) {
    websocket.value.close(3000, "强制关闭");
  }
};

const sendMessage = () => {
  if (chatUser === '') {
    alert("请先选择聊天对象");
    return;
  }
  if (websocket.value && message.value) {
    //为了把发送人名字返回回去，所以多增加变量
    let fullMessage = {from:username,content:message.value,to:chatUser,ifchange:chartchange};
    chartchange = 0;
    // websocket.value.send(message.value);
    websocket.value.send(JSON.stringify(fullMessage));

    // 将发送的消息保存到对应的聊天对象的 sessionStorage 中
    let existingMessages = JSON.parse(sessionStorage.getItem(`${username}_${chatUser}Messages`)) || [];  // 修改这里
    existingMessages.push(fullMessage);
    sessionStorage.setItem(`${username}_${chatUser}Messages`, JSON.stringify(existingMessages));  // 修改这里


    //因为你既作为发送方也作为接收方，所以，所以，你收到了两条信息，that it，自己渲染了两次
    createContent2(null,username,message.value);
    message.value = ''; // Clear input after sending
  }
};

//我最后要用  createContent 来代替 setMessageInHtml
//控制了 setMessageInHtml 就控制了 receivedMessage 就决定了聊天框中显示的格式和内容
//毋庸置疑，必须变成html格式

const createContent2 = (remoteUser, nowUser, message) => {
  let html;

  if ((nowUser === username && chartchange === 0) || (nowUser === username && remoteUser === null)) {  // 判断当前用户是否为发送者且是新发送的消息，或者是查看历史时只有当前用户发送的消息
    html = `<div class="el-row chat-message" style="padding: 5px 0">
              <div class="el-col el-col-22" style="text-align: right;padding-right: 10px">
                <div style="font-size: 12px;">${nowUser}</div>
                <div class="message-bubble tip right" style="background-color: forestgreen; border-radius: 10px; font-family: sans-serif; padding: 10px; color: white; display:inline-block!important;display:inline;">
                  ${message}
                </div>
              </div>
              <div class="el-col el-col-2" >
                <span class="el-avatar el-avatar--circle" style="height: 55px; width: 55px; line-height: 55px;">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
                </span>
              </div>
            </div>`;
  } else if (remoteUser) {
    html = `<div class="el-row chat-message" >
              <div class="el-col el-col-2">
                <span class="el-avatar el-avatar--circle" style="height: 55px; width: 55px; line-height: 55px;">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
                </span>
              </div>
              <div class="received-message" style="text-align: left;padding-left: 10px">
                <div style="font-size: 12px;">${remoteUser}</div>
                <div class="message-bubble tip left" style="background-color: deepskyblue; border-radius: 10px; font-family: sans-serif; padding: 10px; color: white; display:inline-block!important;display:inline;">
                  ${message}
                </div>
              </div>
            </div>`;
  }

  console.log(html);
  receivedMessage.value += html;
};

function getMessagesForChatUser(chatUser) {
  let key = `${username}_${chatUser}Messages`;  // 修改这里，将用户名包含在键中
  let messages = JSON.parse(sessionStorage.getItem(key)) || [];
  return messages;
}

onMounted(() => {
// 从当前聊天对象的 sessionStorage 中获取聊天记录并设置到 receivedMessage
  if (chatUser) {
    let existingMessages = getMessagesForChatUser(chatUser);
    existingMessages.forEach(message => {
      createContent2(message.from, message.to === username? username : null, message.content);
    });
  }


  if ('WebSocket' in window) {
    websocket.value = new WebSocket("ws://127.0.0.1:8086/websocket/"+username);
    // websocket.value = new WebSocket("ws://127.0.0.1:8789/websocket");

    websocket.value.onerror = () => {
      console.log("发送报错");
      setMessageInHtml("send error！");
    };

    websocket.value.onopen = () => {
      console.log("发送成功");
      setMessageInHtml("(欢迎来到聊天室！)");
    };

    //这个是信息发送后端方法
    // websocket.value.onmessage = (event) => {
    //   // setMessageInHtml(event.data);
    //   if (JSON.parse(event.data).from !== username) {
    //     let content = JSON.parse(event.data).content;
    //     createContent2(JSON.parse(event.data).from,null,content);
    //   }
    // };

    //  浏览器端收消息，获得从服务端发送过来的文本消息
    // websocket.value.onmessage = (msg) =>{
    websocket.value.onmessage = function(msg){
      console.log("收到数据====data解析前" + msg.data)
      let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
      // let data = msg.data  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
      console.log("data解析后数据====" + data)
      if (data.users) {  // 获取在线人员信息
        console.log("data.users数据====" + data.users)
        users = data.users.filter(user => user.username !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
        // users = msg.data
        console.log("赋值后users====" + users)
        // users = JSON.parse(users)
        // const username2 = users[0].username;
        const username3 = data.users[0].username;
        // console.log("赋值后2====" + username2)
        console.log("赋值后3====" + username3)
        // console.log("users2lenth====" + users2lenth)
        // console.log("users.length====" + users.length)
        //想数组变化就刷新一下（但是一直刷，失败）
        if (users2lenth !== users.length) {
          users2lenth = users.length;
          // window.location.reload();
          console.log("users2lenth====" + users2lenth)
          console.log("users.length====" + users.length)
        }
        loading.value = false;
      } else {
        console.log("====" + data.ifchange)
        console.log("====" + chartchange)
        if (data.from !== username) {
          if (data.to === username && data.ifchange === 1) {
            chartchange = 0
            chatUser = data.from;
            receivedMessage.value = '';
            console.log("变化了：跟具体用户聊")
          } else if (data.ifchange === 1)
          {
            chartchange = 0
            chatUser = '';
            receivedMessage.value = '';
            console.log("变化了：它跟别人聊去了")
          }
          let content = data.content;

          // 将接收的消息保存到对应的聊天对象的 sessionStorage 中
          let existingMessages = JSON.parse(sessionStorage.getItem(`${username}_${data.from}Messages`)) || [];  // 修改这里
          existingMessages.push({from: data.from, content: content, to: data.to, ifchange: data.ifchange});
          sessionStorage.setItem(`${username}_${data.from}Messages`, JSON.stringify(existingMessages));  // 修改这里

          createContent2(data.from,null,content);
        }
      }
    };

    websocket.value.onclose = () => {
      setMessageInHtml("closed websocket!");
    };
  } else {
    alert("您的浏览器不支持websocket");
  }

  window.addEventListener('beforeunload', closeConnection);
});



onBeforeUnmount(() => {
  closeConnection();
});
</script>

<style scoped>
/* 可选的样式 */
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width:auto;
  display:inline-block !important;
  display:inline;
}
.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
</style>
